package middlwares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/yyangl/yoyo/e"
	"github.com/yyangl/yoyo/utils"
	"net/http"
	"time"
)

func AuthMiddleware(secret string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var code int
		code = e.Success
		token := ctx.GetHeader("Authorization")
		fmt.Printf("AuthMiddleware")
		if token == "" {
			code = e.ErrorNotExistToken
		} else {
			claims, err := utils.ParseToken(token, secret)
			fmt.Printf("ParseToken")
			if err != nil {
				fmt.Printf("err = %s", err.Error())
				code = e.ErrorAuthCheckTokenFail
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = e.ErrorAuthCheckTokenTimeout
			} else if claims != nil {
				ctx.Set("uid", claims.Uid)
				ctx.Next()
			}
		}
		if code != e.Success {
			ctx.JSON(http.StatusOK, gin.H{
				"code": code,
				"msg":  e.GetMeg(code),
			})
			ctx.Abort()
			return
		}

	}
}
